package com.zhkeshe.keshe.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhkeshe.keshe.Service.UserDeviceService;
import com.zhkeshe.keshe.Service.UserService;
import com.zhkeshe.keshe.entity.CommonResult;
import com.zhkeshe.keshe.entity.FengShanUse;
import com.zhkeshe.keshe.entity.User;
import com.zhkeshe.keshe.mapper.FengShanUseMapper;
import com.zhkeshe.keshe.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.zhkeshe.keshe.Socket.WebSocketServer.isOnline_ws;

@CrossOrigin
@RestController
public class UserDeviceController {
    @Autowired
    private FengShanUseMapper fengShanUseMapper;
    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/UserDevice/DeviceCommand")
    Object DeviceCommand(@RequestBody Map<String,String> data) throws IOException {
        //System.out.println(data);
        return userDeviceService.CommandHandle(data);
    }
    @RequestMapping("/UserDevice")
    Object UserDevice(@RequestBody Map<String,String> data){
        return userDeviceService.bind(data);
    }

    @RequestMapping("/getView")
    Object getView(String user){
        Map<String,Object> map=new HashMap<>();

        FengShanUse fengShanUse= null;
        try {
            User user1 = userMapper.selectByUserName(user);
            fengShanUse = fengShanUseMapper.selectByUserID(Math.toIntExact(user1.getId()));
        } catch (Exception e) {
            map.put("status",false);
            return map;
        }
        JSONArray jsonArray=new JSONArray();
        JSONObject jsonObject=JSONObject.parseObject(JSONObject.toJSONString(fengShanUse));
        for(String e:jsonObject.keySet()){
            JSONObject jsonObject1=new JSONObject();
            // { value: 1048, name: 'Search Engine' },
            if(e.equals("userId")){
                continue;
            }
            jsonObject1.put("value",jsonObject.get(e));
            jsonObject1.put("name",e);
            jsonArray.add(jsonObject1);
        }
        map.put("status",true);
        map.put("arr",jsonArray);
        return map;
    }
    @RequestMapping("/UserDevice/IsDeviceOnline")
    Object isOnline(String deviceId){
        CommonResult commonResult=new CommonResult();
        commonResult.setStatus(isOnline_ws(deviceId));
        commonResult.setMessage("verify??");
        commonResult.setDeviceList(new ArrayList<>());
        return commonResult;
    }


}
